<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="请输入员工名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <!-- <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button> -->
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        size="small"
        icon="el-icon-download"
        @click="handleDownload"
      >
        导出表格(页面)
      </el-button>
      <el-button v-waves class="filter-item" type="primary" size="small"
        >批量导入</el-button
      >
    </div>
    <!-- 导入对话框 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="importDialogFormVisible"
      width="50%"
      @close="cleanAssignFormData"
    >
      <el-card>
        <el-upload
          class="upload-demo"
          drag
          action="#"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="fileList"
          multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            拖拽或者 <em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            表格记录建议不超过1000条
          </div>
        </el-upload>
      </el-card>
      <!-- <el-form
        ref="assignForm"
        :rules="assignRules"
        :model="assignForm"
        label-position="left"
        label-width="85px"
        style="width: 80%; margin-left:50px;"
      >
        <el-checkbox-group v-model="assignForm.roleIds">
          <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">{{
            item.name
          }}</el-checkbox>
        </el-checkbox-group>
      </el-form> -->
      <!-- <div slot="footer" class="dialog-footer">
        <el-button @click="importDialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="confirmAssign">
          确认
        </el-button>
      </div> -->
    </el-dialog>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="序号" type="index"></el-table-column>
      <el-table-column label="姓名" prop="username"></el-table-column>
      <el-table-column label="手机号" prop="mobile"></el-table-column>
      <el-table-column label="工号" prop="jobNumber"></el-table-column>
      <el-table-column label="聘用形式" prop="employmentForm"></el-table-column>
      <el-table-column label="部门" prop="departmentName"></el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="400"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button size="mini" @click="showDetail(row.id)">
            查看
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row.id)">
            删除
          </el-button>
          <el-button type="warning" size="mini" @click="showAssign(row)">
            分配角色
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="50%"
      @close="cleanFormData"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-position="left"
        label-width="85px"
        style="width: 80%; margin-left:50px;"
      >
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="assignDialogFormVisible"
      width="50%"
      @close="cleanAssignFormData"
    >
      <el-form
        ref="assignForm"
        :rules="assignRules"
        :model="assignForm"
        label-position="left"
        label-width="85px"
        style="width: 80%; margin-left:50px;"
      >
        <el-checkbox-group v-model="assignForm.roleIds">
          <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">{{
            item.name
          }}</el-checkbox>
        </el-checkbox-group>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignDialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="confirmAssign">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table
        :data="pvData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  createUser,
  updateUser,
  queryAllRoles,
  assignRoles
} from "@/api/user/index.js";
import waves from "@/directive/waves"; // waves directive
import { parseTime, cleanEmptyValue } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

export default {
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger"
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        name: null
        // importance: undefined,
        // title: undefined,
        // type: undefined,
        // sort: "+id"
      },
      roles: [],
      importanceOptions: [1, 2, 3],

      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" }
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      form: {},
      rules: {
        name: [{ required: true, message: "必填项", trigger: "blur" }]
      },

      state: true,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "修改",
        create: "添加",
        assign: "分配角色",
        import: "批量导入"
      },
      dialogPvVisible: false,
      pvData: [],
      downloadLoading: false,
      assignDialogFormVisible: false,
      assignRules: {},
      assignForm: {
        id: "",
        roleIds: []
      },
      importDialogFormVisible: false,
      fileList: []
    };
  },
  created() {
    this.getList();
    this.getRoles();
    // this.queryDistricts();
  },
  methods: {
    getList() {
      this.listLoading = true;
      if (!this.listQuery.name) {
        delete this.listQuery.name;
      }
      fetchList(this.listQuery).then(response => {
        // console.log(response);
        this.list = response.page.list;
        this.total = response.page.totalCount;
        this.listLoading = false;
      });
    },
    getRoles() {
      queryAllRoles({ companyId: "1343916938447523840" }).then(resp => {
        // console.log(resp);
        this.roles = resp.roles;
      });
    },

    showAssign(row) {
      // console.log(row);
      this.assignForm.id = row.id;
      this.assignForm.roleIds = row.roles.map(i => i.id);
      console.log(this.assignForm.roleIds);
      this.dialogStatus = "assign";
      this.assignDialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["assignForm"].clearValidate();
      });
    },
    confirmAssign() {
      assignRoles(this.assignForm).then(resp => {
        this.getList();
        this.assignDialogFormVisible = false;
      });
    },
    cleanAssignFormData() {
      this.assignForm.id = "";
      this.assignForm.roleIds = [];
    },
    showDetail(id) {
      this.$router.push(`/user/detail/${id}`);
    },
    handleFilter() {
      this.getList();
    },

    handleModifyStatus(row, status) {
      this.$message({
        message: "操作Success",
        type: "success"
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    handleCreate() {
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    createData() {
      // console.log(this.form);
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          cleanEmptyValue(this.form);
          createUser(this.form).then(() => {
            this.dialogFormVisible = false;
            this.getList();
          });
        }
      });
    },

    handleUpdate(row) {
      this.form = Object.assign({}, row); // copy obj
      this.districts = this.form.area.split("-");
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          cleanEmptyValue(this.form);
          updateUser(this.form).then(() => {
            this.getList();
            this.dialogFormVisible = false;
          });
        }
      });
    },
    cleanFormData() {
      this.$refs["dataForm"].resetFields();
      this.districts = [];
      this.industries = [];
    },
    handleDelete(id) {
      console.log(id);
      // 删除用户
      // 删除用户角色桥表数据
      // 更改用户状态：禁用
    },

    // 批量导入
    //
    cleanImportFormData() {},
    // 预览
    handlePreview() {},
    // 移除
    handleRemove() {},


    // 页面导出
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData;
        this.dialogPvVisible = true;
      });
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["timestamp", "title", "type", "importance", "status"];
        const filterVal = [
          "timestamp",
          "title",
          "type",
          "importance",
          "status"
        ];
        const data = this.formatJson(filterVal);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list"
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    }
  }
};
</script>
<style scoped>
/deep/ .industry input::-webkit-input-placeholder {
  color: #717171 !important;
}
/deep/ .industry input::-moz-placeholder {
  /* Mozilla Firefox 19+ */
  color: #717171 !important;
}
/deep/ .industry input:-moz-placeholder {
  /* Mozilla Firefox 4 to 18 */
  color: #717171 !important;
}
/deep/ .industry input:-ms-input-placeholder {
  /* Internet Explorer 10-11 */
  color: #717171 !important;
}
</style>
